<!--
 * @title: 导出excel组件
 * @author: andy.ten@tom.com & xukaixing@hotmail.com
 * @Date: 2022-04-23 18:46:10
 * @LastEditors: andy.ten@tom.com
 * @LastEditTime: 2022-06-06 11:45:34
 * @version: 1.0.9
 * @copyright: copyright (c) 2022 andyten
 *  node: you can not copy and/or use and/or modify this program free,
 *  please reserve the segment above.Please mail me if you have any question.
-->

<template>
  <ht-dialog title="导出列表数据" :visible.sync="isVisible">
    <div class="ht-export-dialog">
      <ht-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</ht-checkbox>
      <div style="margin: 5px 0;" />
      <ht-checkbox-group v-if="isVisible" v-model="checkedFields" @change="handleCheckedChange">
        <ht-checkbox v-for="head in tabFields" :key="head.prop" class="ht-field" :label="head.prop">{{ head.label }}</ht-checkbox>
      </ht-checkbox-group>
    </div>
    <template #footer>
      <ht-button type="primary" @click="handleConfirm">确 定</ht-button>
    </template>
  </ht-dialog>
</template>
<script>
import { toLine } from '@/utils';
export default {
  name: 'HtExportDialog',
  props: {
    visible: {
      type: Boolean,
      required: false,
      default: false
    },
    tableHead: {
      type: Array,
      required: true
    },
    refTable: {
      type: String,
      required: true
    },
    export: {
      type: Function,
      required: true
    },
    findExportFields: {
      type: Function,
      required: true
    },
    saveExportFields: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      tabFields: [],
      checkAll: true,
      checkedFields: [],
      checkedFieldsLabel: [],
      isVisible: this.visible,
      isIndeterminate: false,
      recordsList: [],
      expId: '',
      confirm: false // 是否确定按钮点击标识
    };
  },
  watch: {
    visible(newVal, oldVal) {
      this.confirm = false;
      this.isVisible = newVal;
    },
    isVisible(newValue, oldValue) {
      if (this.isVisible === true) {
        this.confirm = false;
        this.tabFields = this.tableHead;
        this.setCheckedFields();
      } else if (this.confirm === false) // 点击取消按钮响应
        // 去掉导出按钮的loading效果
        this.$parent.$refs['ht-table-' + this.refTable].$parent.exportBtnLoading = false;

      // console.log(this.$parent);
      // this.$emit('updateDialogShow', newValue);
      this.$parent.updateDialogShow(newValue);
    },
    tableHead(newVal, oldVal) {
      // console.log(this.tableHead);
    }
  },
  created() {
    if (this.isVisible === true) {
      this.tabFields = this.tableHead.filter((x) => {
        return x.label !== '操作';
      });
      // 查询 已保存的导出列
      this.findExportedFields();
    }
  },
  mounted() {
  },
  methods: {
    async findExportedFields() {
      try {
        const result = await this.findExportFields(this.refTable);
        this.recordsList = result.datas;
        this.setCheckedFields();
      } catch (error) {
        this.$notify.message(error, 'error');
      }
    },
    setCheckedFields() {
      if (this.recordsList && this.recordsList.length > 0) {
        const expKeysArr = this.recordsList[0].exp_keys.split(',');
        this.expId = this.recordsList[0].id;
        this.tabFields.map((x) => {
          if (x.type !== 'action' && x.type !== 'link')
            if (expKeysArr.includes(toLine(x.prop))) {
              this.checkedFields.push(x.prop);
              this.checkedFieldsLabel.push(x.label);
            }
        });
      } else
        this.tabFields.map((x) => {
          this.checkedFields.push(x.prop);
          this.checkedFieldsLabel.push(x.label);
        });
      if (this.checkedFields.length !== this.tabFields.length)
        this.isIndeterminate = true;
    },

    handleCheckAllChange(val) {
      if (val)
        this.tabFields.map((x) => {
          this.checkedFields.push(x.prop);
          this.checkedFieldsLabel.push(x.label);
        });
      else {
        this.checkedFields = [];
        this.checkedFieldsLabel = [];
      }

      this.isIndeterminate = false;
    },
    /**
     * @todo: 选中变化事件
     * @author: andy.ten@tom.com & xukaixing@hotmail.com
     * @Date: 2022-04-25 08:18:37
     * @param {*} checkedArr Array 已被选中的checkbox prop
     */
    handleCheckedChange(checkedArr) {
      const checkedCount = checkedArr.length;
      this.checkAll = checkedCount === this.tabFields.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tabFields.length;
      // 设置label
      const changeChecked = this.tabFields.filter((x) => {
        if (x.prop === checkedArr[checkedCount - 1])
          return true;
      });
      this.checkedFields.push(changeChecked[0].prop);
      this.checkedFieldsLabel.push(changeChecked[0].label);
    },
    async handleConfirm() {
      // 获取选中的fields
      this.confirm = true;
      let fields = '';
      this.checkedFields.forEach((x, index) => {
        if (fields === '')
          fields = toLine(x) + '|' + this.checkedFieldsLabel[index];
        else fields += ',' + toLine(x) + '|' + this.checkedFieldsLabel[index];
      });
      // 获取列表查询条件
      const tableNode = this.$parent.$children.filter((x) => {
        if (x.$vnode.componentOptions && x.$vnode.componentOptions.tag === 'el-table')
          return true;
      });
      let filterConditions = {};
      if (tableNode && tableNode[0])
        filterConditions = tableNode[0].$parent.filterConditions;
      const param = { header: fields, btnid: this.refTable, exportid: this.expId, params: JSON.stringify(filterConditions) };
      this.isVisible = false;
      await this.export(param).then((res) => {
        // 设置导出按钮状态
        this.$parent.$refs['ht-table-' + this.refTable].$parent.exportBtnLoading = false;
        this.$parent.$refs['ht-table-' + this.refTable].$parent.exportBtnDisabled = true;
        if (res && res.data) {
          let fileName = '导出数据.xlsx';
          if (res.headers['content-disposition'])
            fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]);
          const blob = new Blob([res.data], {
            type: 'application/octet-stream'
          });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          // 兼容ie
          if (!!window.ActiveXObject || 'ActiveXObject' in window)
            window.navigator.msSaveOrOpenBlob(blob, link.download);
          else
            link.click();
          link.remove();
          window.URL.revokeObjectURL(url);
          this.$notify.message('导出数据成功', 'success');
          // 保存导出列信息
          this.saveExportFields(this.refTable, fields, this.expId);
          // } else {
          //   this.$notify.alert('导出excel错误: 返回数据不正确', 'error');
          // }
        } else
          this.$notify.alert('导出excel错误: 返回数据不正确', 'error');
      });
      this.loading = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.ht-export-dialog{
  width: 100%;

  .ht-field{
    width: 16%;
    padding:8px 2px;
  }

  ::v-deep .ht-field.is-checked{
    .el-checkbox__label{
      color: $textColor;
    }

  }
}
</style>
